import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

class User{
    //当前属性都设置成public
    public int userId;
    public int classId;
}




@WebServlet("/postJson")
public class PostJsonServlet extends HttpServlet {

    //1.创建一个Jackson对象
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //2.读取body中的请求，使用ObjectMapper来解析需要的对象
        //readValue就是把JSON格式的字符串，转换成Java的对象
        //第一个参数表示对那个字符串进行转换，这个参数可以填写承一个String，也可以填写InputStream对象，还可以填一个file
        //第二个表示把那个JSON格式的字符串转成那个Java对象
        User user = objectMapper.readValue(req.getInputStream(),User.class);
        resp.getWriter().write("userId = "+user.userId+",  classId = "+user.classId);


    }
}


















